package com.java1412.service.impl;

import com.java1412.dao.db2.UserRepository;
import com.java1412.entity.db2.User;
import com.java1412.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * 注意:此处一定要通过@Transactional注解来明确指明所用的事务管理器,否则当多数据源时可能只能执行一个数据里的增删改操作.
 * 且此处应该设置Spring的事务传播属性为propagation =Propagation.NEVER,不使用单个数据源自己的事务,统一交由jtaTransactionManager的事务来管理.
 * @author java1412
 * @create 2021-07-07 16:59
 */
@Service
@Transactional(transactionManager = "userTransactionManager", rollbackFor = Exception.class, propagation = Propagation.NEVER)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }
    @Override
    public User addUser(User user) {
        try {
            return userRepository.save(user);
        } catch (Exception e) {
            //强制手动事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return null;
    }
}